// pages/chat/chat.js
import {
  formatTime
} from "../../utils/util.js";
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {

    emoji: ['😊', '😅', '😲', '😭', '😂', '😄', '😩', '😞', '😵', '😒', '😍',
      '😤', '😜', '😝', '😋', '😘', '😚', '😷', '😳', '😃', '😆', '😁', '😢', '😨',
      '😠', '😣', '😌', '😖', '😔', '😰', '😱', '😪', '😏', '😓'
    ],
    isShowEmoji: false,
    content: '',
    from_user_id: 0,
    to_user_id: 0,
    all_list: [],
    interval: 0,
    userInfo: [],
    next: 0,
    scrollTop: 300,
    windowHeight: 0, //页面高度
    isContent: true,
    imageId: '',
    url_id: '',
    temp: 0,
    mysure: [],
    mytime: [],
    myday: [],
    times: [],
    flag: true,
    showtime: "",
    disabled: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var user_id = wx.getStorageSync("user_id")
    var from_user_id = options.from_user_id;
    var to_user_id = options.to_user_id;
    that.setData({
      'from_user_id': from_user_id,
      'to_user_id': to_user_id,
      'user_id': user_id,
      nowSkinUrl: app.globalData.nowSkinUrl
    });
    var id_list = [];
    id_list.push(from_user_id)
    id_list.push(to_user_id)
    wx.request({
      url: app.globalData.targetUrl + 'users/',
      method: 'get',
      data: {
        'user_list': id_list
      },
      success: res => {

        that.setData({
          'from_avatar': res.data.data[0].avatar_url,
          'to_avatar': res.data.data[1].avatar_url
        });
        that.setData({
          userInfo: res.data.data
        })
        that.onLoadChats();
        wx.setNavigationBarTitle({
          title: that.data.userInfo[1].nick,
        });
      }
    })
  },

  //点击对方头像跳转到个人信息页面
  onToPeopleFromMsg: function(){
    var that = this;
    wx.navigateTo({
      url: '/pages/my/personalMsg?user_id=' + that.data.to_user_id,
    })
  },

  //点击自己头像跳转到个人信息页面
  onToPeopleMsg: function () {
    var that = this;
    wx.navigateTo({
      url: '/pages/my/personalMsg?user_id=' + that.data.user_id,
    })
  },

  //将年、月、日字符串变成数字，以便比较
  day_time_num: function (time) {
    var that = this;
    var temp = time[2] * 100000 + time[3] * 10000 + time[5] * 1000 + time[6] * 100 + time[8] * 10 + time[9] * 1;
    that.setData({
      temp: temp
    });
  },

  //将小时、分钟变成数字，以便比较
  minute_time_num: function (time) {
    var that = this;
    var temp = time[11] * 1000 + time[12] * 100 + time[14] * 10 + time[15] * 1;
    that.setData({
      temp: temp
    });
  },

  //比较时间，最终的显示出来
  Showtime: function (data, index, myday, mysure, mytime, times, str) {
    var that = this;
    that.minute_time_num(data[index - 1].created_time);
    var ahead = that.data.temp;
    that.minute_time_num(data[index].created_time);
    var next = that.data.temp;
    that.setData({
      next: next,
      ahead: ahead
    })
    if (ahead <= next - 5) {
      mysure[index] = 1;
      var time = data[index].created_time;
      mytime[index] = time[11] + time[12] + time[13] + time[14] + time[15];
      myday[index] = str;
      times[index] = 0;
      that.setData({
        mysure: mysure,
        mytime: mytime,
        myday: myday,
        times: times
      });
    } else {
      mysure[index] = 0;
      mytime[index] = "";
      myday[index] = "";
      times[index] = 0;
      that.setData({
        mysure: mysure,
        mytime: mytime,
        myday: myday,
        times: times
      });
    }
  },

  //在消息记录里隔5分钟以上即会显示下一条发消息的时间
  setChatTime: function (data) {
    var that = this;
    var ahead = 0;
    var next = 0;
    var mysure = [];
    mysure[0] = 0;
    var mytime = [];
    mytime[0] = "";
    var myday = [];
    myday[0] = "";
    var times = [];
    times[0] = 0;
    var str = "";
    var time = "";
    for (var index = 1; index < data.length; index++) {
      that.day_time_num(formatTime(new Date())); //当前时间
      ahead = that.data.temp;
      that.day_time_num(data[index].created_time);
      next = that.data.temp;
      time = data[index].created_time;
      if (ahead == next) {
        str = "今天";
        that.Showtime(data, index, myday, mysure, mytime, times, str);
      } else if (ahead == next - 1) {
        str = "昨天";
        that.Showtime(data, index, myday, mysure, mytime, times, str);
      } else {
        str = time[5] + time[6] + time[7] + time[8] + time[9];
        that.Showtime(data, index, myday, mysure, mytime, times, str);
      }
    }
  },

  //加载后面发消息的时间
  loadChatTime: function (data, len, length) {
    var that = this;
    that.minute_time_num(data[len].created_time);
    var ahead = that.data.temp;
    that.minute_time_num(data[length].created_time);
    var next = that.data.temp;
    var mysure = that.data.mysure;
    var times = that.data.times;
    mysure[length] = 0;
    that.setData({
      mysure: mysure
    });
    if (ahead <= next - 5) {
      times[length] = 1;
      that.setData({
        times: times
      });
      var time = data[length].created_time;
      var showtime = time[11] + time[12] + time[13] + time[14] + time[15];
      that.setData({
        showtime: showtime
      });
    } else {
      times[length] = 0;
      that.setData({
        times: times
      });
    }
  },

  // 刷新聊天数据
  onLoadChats: function () {
    var that = this;
    wx.request({
      url: app.globalData.targetUrl + 'wx/chat/',
      method: 'get',
      header: {
        'content-type': 'application/json'
      },
      data: {
        'from_user_id': that.data.from_user_id,
        'to_user_id': that.data.to_user_id
      },
      success: res => {
        var all_list = res.data.data;
        console.log("219--刷新聊天")
        for (var i = 0; i < all_list.length; i++) {
          all_list[i].content = that.entitiesToUtf16(all_list[i].content);
        }
        //all_list.content = that.entitiesToUtf16(all_list.content);
        //res.data.data.content = that.entitiesToUtf16(res.data.data.content);
        that.setData({
          all_list: all_list
        });


        if (that.data.len != res.data.data.length) {
          if (that.data.flag) {
            that.setChatTime(res.data.data); ///设置时间
            var flag = false;
            that.setData({
              flag: flag,
            });
          } else {
            var flag1 = 1;
            that.setData({
              flag1: flag1,
            });
            if (that.data.len == 0) {
              that.loadChatTime(res.data.data, that.data.len, res.data.data.length - 1);
            } else {
              that.loadChatTime(res.data.data, that.data.len - 1, res.data.data.length - 1);
            }
          }
          that.setData({
            len: res.data.data.length,
            scrollTop: 1000 * res.data.data.length
          })
          wx.hideLoading();
        }
      }
    });
  },

  onClickInput: function () {
    var that = this;
    that.setData({
      isShowEmoji: false
    });
  },

  // 发信框
  onChatInput: function (e) {
    var that = this;
    that.setData({
      isShowEmoji: false
    });
    var content = e.detail.value;
    if (e.detail.value.length > 39) {
    }
    that.setData({
      content: content,
    });
  },

  getNowFormatDate: function () {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var currentdate = month + seperator1 + strDate +
      " " + date.getHours() + seperator2 + date.getMinutes() +
      seperator2 + date.getSeconds();
    return currentdate;
  },
  // 发送一条聊天
  sendChat: function () {
    var that = this;

    var content = that.data.content;
    that.setData({
      content: ''
    })
    content = that.utf16toEntities(content);
    wx.request({
      url: app.globalData.targetUrl + 'wx/chat/',
      method: 'post',
      header: {
        'Content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        'from_user_id': that.data.from_user_id,
        'to_user_id': that.data.to_user_id,
        'content': content,
        'image_id': that.data.imageId
      },
      success: res1 => {
        var to_openid = res1.data.data['to_openid'];
        console.log("319-"+to_openid)
        that.setData({
          to_openid: to_openid
        })
        var my_openid = wx.getStorageSync("openid");
        // 聊天成功, 进行模版消息推送
        var user_id = wx.getStorageSync('user_id');
        var formId = that.data.formId;
        console.log("454-that.data.to_user_id" + that.data.to_user_id)
        app.saveFormId(user_id, formId);
        wx.request({
          url: app.globalData.targetUrl + 'wx/form_id/',
          method: 'get',
          data: {
            'user_id': that.data.to_user_id
          },
          success: res => {
            console.log("464.res=")
            console.log(res.data);
            var formId = res.data.data.form_id;
            console.log("推送-" + formId)
            console.log("---" + that.data)
            wx.request({
              url: app.globalData.targetUrl + 'wx/message/',
              method: 'post',
              header: {
                'Content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                'touser': that.data.to_openid,
                'form_id': formId,
                'keywords': JSON.stringify(['民大点点', "您收到一条新消息", that.getNowFormatDate()])
              },
              success: res => {
                console.log("478-推送的结果");
              }

            })
          }
        })
        /*console.log(res1.data.data['to_openid']);
        var my_openid = wx.getStorageSync("openid");
        // 聊天成功, 进行模版消息推送
        var user_id = wx.getStorageSync('user_id');
        app.refreshFormId(user_id, formId);
        wx.request({
          url: app.globalData.target_url + 'wx/get_info?user_id=' + that.data.to_user_id,
          success:function(res){
            console.log(res);
            console.log(res.data.data['form_id']);
            wx.request({
              url: app.globalData.target_url + 'wx/message/',
              method: 'post',
              header: {
                'Content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                //'touser': 'o52Q_5fKII2Uf9xKATf8KNrQI-Kg',
                'touser': res1.data.data['to_openid'],
                //'touser': my_openid,
                //'form_id': formId,
                //'touser': "o52Q_5Zm-AMdzLflt0HfDsDoUW7g",
                'form_id': res.data.data['form_id'],
                'keywords': JSON.stringify(['民大点点', that.data.content, that.getNowFormatDate()])
              },
              success: res => {*/
        //console.log(res.data);
        var mywant = 1;
        wx.setStorageSync('mywant', mywant);
        that.setData({
          imageId: ''
        });
        that.onLoadChats(); //刷新聊天数据
        // 更新列表顺序
        wx.request({
          url: app.globalData.targetUrl + 'wx/chat_list/',
          method: 'post',
          header: {
            'Content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            'user_id': that.data.user_id,
            'with_user_id': that.data.to_user_id
          },
          success: res => {
            // 获取最新信息, 设置是否为自己发送的信息
            wx.request({
              url: app.globalData.targetUrl + 'wx/chat_list/',
              method: 'get',
              header: {
                'content-type': 'application/json'
              },
              data: {
                'user_id': that.data.user_id
              },
              success: res => {
                var is_my_message = [];
                var chat_list = res.data.data;
                //console.log(chat_list);
                for (var i = 0; i < chat_list.length; i++) {
                  // 如果有这条记录
                  if (chat_list[i].with_id == that.data.to_user_id) {
                    is_my_message.push(true);
                  } else {
                    is_my_message.push(false); //这条最新记录不是我刚发的
                  }
                }
                wx.setStorageSync("is_my_message", is_my_message);
              }
            });
          }
        });
      }
    });
    //}
    //})

    //}
  },

  // 点击发送
  onSendClick: function (e) {
    var that = this;
    var time = 3;
    that.setData({
      disabled: true
    })
    var Interval = setInterval(function () {
      time--;
      if (time > 2) {
        that.setData({
          disabled: true
        })
      } else {
        clearInterval(Interval);
        that.setData({
          disabled: false
        })
      }
    }, 1000)
    if (that.data.content == '') {
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '不能发送空信息',
      })
    } else {
      that.setData({
        isContent: true,
        formId: e.detail.formId
      })

      that.sendChat();

      //判断当前发送消息和上面chat_list最后一条信息的时间差
      var next = that.data.next;
      var nowTime = formatTime(new Date());
      console.log("439-onSendClick-nowTime")
      console.log(nowTime);
      that.minute_time_num(nowTime);
      var head = that.data.temp;
      console.log("443-next"+next)
      console.log("444-head"+head)
      if (head - next >= 0) {
        that.setData({
          next: head
        })
        console.log("449-进来")
        console.log("455-that.data=" + that.data)
        /*var my_openid = wx.getStorageSync("openid");
        // 聊天成功, 进行模版消息推送
        var user_id = wx.getStorageSync('user_id');
        var formId = that.data.formId;
        console.log("454-that.data.to_user_id" + that.data.to_user_id)
        app.saveFormId(user_id, formId);       
        wx.request({
          url: app.globalData.targetUrl + 'wx/form_id/',
          method: 'get',
          data: {
            'user_id': that.data.to_user_id
          },
          success: res => {
            console.log("464.res=")
            console.log(res.data);
            var formId = res.data.data.form_id;
            console.log("推送-"+formId)
            console.log("---" + that.data)
            wx.request({
              url: app.globalData.targetUrl + 'wx/message/',
              method: 'post',
              header: {
                'Content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                'touser': that.data.to_openid,
                'form_id': formId,
                'keywords': JSON.stringify(['民大点点', "您收到一条新消息", that.getNowFormatDate()])
              },
              success: res => {
                console.log("478-推送的结果");
              }

            })
          }
        })*/
      }
      wx.pageScrollTo({
        scrollTop: 1100
      });
    }
  },
  //把utf16的emoji表情字符进行转码成八进制的字符

  utf16toEntities: function (str) {

    var patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则  

    return str.replace(patt, function (char) {

      var H, L, code;

      if (char.length === 2) {

        H = char.charCodeAt(0); // 取出高位  

        L = char.charCodeAt(1); // 取出低位  

        code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法  

        return "&#" + code + ";";

      } else {

        return char;

      }

    });

  },



  //将编码后的八进制的emoji表情重新解码成十六进制的表情字符

  entitiesToUtf16: function (str) {

    return str.replace(/&#(\d+);/g, function (match, dec) {

      let H = Math.floor((dec - 0x10000) / 0x400) + 0xD800;

      let L = Math.floor(dec - 0x10000) % 0x400 + 0xDC00;

      return String.fromCharCode(H, L);

    });

  },

  //显示表情列表
  onSendEmoji: function (e) {
    var that = this;
    if (that.data.isShowEmoji == false) {
      that.setData({
        isShowEmoji: true
      })
    } else {
      that.setData({
        isShowEmoji: false
      })
    }

    wx.pageScrollTo({
      scrollTop: 1500
    })

  },
  //点击表情
  onClickEmoji: function (e) {
    var that = this;
    var id = e.target.id;
    var emoji = that.data.emoji[id];
    //emoji = that.utf16toEntities(emoji);

    var content = that.data.content + emoji;

    that.setData({
      content: content
    })
  },
  onClickScrollView: function (e) {
    var that = this;
    that.setData({
      isShowEmoji: false
    })

  },

  //发送一张图片
  onSendImage: function () {
    var that = this;
    wx.chooseImage({
      count: 1, //最多选择2张图片- that.data.banner.length,
      sizeType: ['compressed'],
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var img = res.tempFilePaths;
      //  console.log(res.tempFilePaths);
        if (res.tempFilePaths.count == 0) {
          return;
        }
        that.setData({
          img: img
        })
        //上传图片
        wx.showLoading({
          title: '图片上传中',
        })
        wx.uploadFile({
          url: app.globalData.targetUrl+ 'upload/image/',
          filePath: that.data.img[0],
          name: 'img',
          header: {
            'Content-type': 'application/x-www-form-urlencoded'
          },
          formData: {
            'user_id': that.data.user_id
          },
          success: function (res) {
            var data = JSON.parse(res.data).data;
            console.log("图片");
            console.log(res);
            that.setData({
              imageId: data.image_id
            })
            wx.hideLoading()
            that.sendChat();
          },
        })
      }
    })
  },

  //图片放大
  previewImage: function (e) {
    var that = this;
    //console.log(e);
    var urls = [];
    urls[0] = e.currentTarget.dataset.src;
    var current = e.target.dataset.src;
    console.log(urls)
    current
    urls[0] = urls[0].slice(0, urls.length - 8) + ".jpg";
    console.log(urls)
    wx.previewImage({
      current: current, // 当前显示图片的http链接 
      urls: urls // 需要预览的图片http链接列表 
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let scrollHeight = wx.getSystemInfoSync().windowHeight;
    this.setData({
      scrollHeight: scrollHeight
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.setData({
      nowSkinUrl: app.globalData.nowSkinUrl
    })
    var isShowEmoji = that.isShowEmoji;
    var mywant = 0;
    wx.setStorageSync('mywant', mywant);
    var label = 1;
    wx.setStorageSync('label', label);
    var that = this;
    that.onLoadChats();
    var len = 0
    if (that.data.inverval != 0) {
      var times = 0
      var id = setInterval(function () {
        that.onLoadChats();
      }, 3000);

      that.setData({
        interval: id,
        isShowEmoji: false
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
   },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    clearInterval(that.data.interval);
    that.setData({
      disabled: false
    })
  }
})